<?php

namespace App\Http\Controllers\Api\v1\Pay;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Service\Pay\TarsPayService;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Exception;

class TarsPayController extends Controller
{
    //充值回调
    public function rechargeNotify(Request $request): string
    {
        try {
            $data = $request->all();
            $header = $request->header("X-RESP-SIGNATURE");
            info('TarsPay收回调参数:'.json_encode($data));
            info("SIGNATURE:".$header);
            if($data['bizType'] != 1){ return "error"; }

            $order = Order::query()->where('no', '=', $data['mchOrderNo'])->first();
            if (!$order || $order->closed == 1) {
                return 'order error';
            }
            $service = new TarsPayService($order);
            if (!$service->checkSign($data, $header)) {
                return 'sign error';
            }
            $paid_at = Carbon::now()->timestamp;
            $state = $data['state'] == 2 ? Order::SUCCESS : Order::FAILED;
            return (new Order())->rechargeComplete($state, $data['mchOrderNo'], '', $paid_at, json_encode($data, JSON_UNESCAPED_UNICODE)) ? 'OK' : 'error';
        } catch (Exception $exception) {
            info('message:' . $exception->getMessage() . ',file:' . $exception->getFile() . ',line:' . $exception->getLine());
            return 'error';
        }
    }

    //提现回调
    public function withdrawalNotify(Request $request): string
    {
        try {
            $arr = $request->all();
            $header = $request->header("X-RESP-SIGNATURE");
            info('TarsPay付回调参数:'.json_encode($arr));
            $order = Order::query()->where('no', '=', $arr['mchOrderNo'])->first();
            if (!$order) {
                return 'order error';
            }
            $service = new TarsPayService($order);
            if (!$service->checkSign($arr, $header)) {
                return 'sign error';
            }
            //$arr['payment_no'] = $arr['withdrawId'];
            $res = (new Order())->withdrawComplete([
                'state' => $arr['state'] == 2 ? Order::SUCCESS : Order::FAILED,
                'orderId' => $arr['mchOrderNo'],
                'paidAt' => Carbon::now()->timestamp
            ], $arr);
            return $res ? 'OK' : 'error';
        } catch (Exception $exception) {
            return 'error';
        }
    }
}
